package com.llcbenwu.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.llcbenwu.security.LoginType;
import com.llcbenwu.security.SecurityProperies;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义成功处理器
 * @author lilinchun
 * @date 2021/10/25 0025 19:29
 */
@Component("llcAuthenticationSuccessHandler")
@Slf4j
//public class llcAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public class    llcAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {



    @Autowired
    private ObjectMapper objectMapper;


    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication 封装请求的信息
     * @throws IOException
     * @throws ServletException
     */

    //登录成功会被调用
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
      log.info("登录成功");
      //如果配置为json返回
      if(LoginType.JSON.equals(SecurityProperies.LOGINTYPE)){
          //将封装的信息以json的格式返回
          httpServletResponse.setContentType("application/json;charset=UTF-8");
          httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
      }else {
          super.onAuthenticationSuccess(httpServletRequest,httpServletResponse,authentication);
      }

    }
}
